import { types, getEnv, flow } from "mobx-state-tree";
import axios from "src/api/index";
import * as config from "src/config/index";
import { Toast } from "antd-mobile";

const cache = {};
const sysList = [
    {
        name: "PQS质量管理体系平台系统",
        path: "/pqs",
        mdTypeId: config.MD_TYPE_ID || 12,
        icon: "el-icon-add",
    },
];

/**
 *  菜单预处理
 * @param state
 * @param menu
 * @returns {Array}
 */
function menuProcess(state, menu) {
    sysList.forEach(item => {
        const name = item.path.replace("/", "");
        item.sysName = name;
        item.dbName = name;
    });
    state.SET_SYS_LIST(sysList);
    return menu;
}

/**
 * 登录后所需的初始化
 * @param context  store 的context
 * @param loginRes 后台返回的数据
 * @param enterSysMsg 需要默认进入的系统名称 空值为单前系统
 */
function afterLogin(context, loginRes, enterSysMsg) {
    const userData = loginRes.data;
    // context.commit("ADD_USER_DATA", userData);
    context.ADD_USER_DATA(userData);
    // context.state.token = userData.webid;
    context.SET_TOKEN(userData.webid);
    sessionStorage.setItem("token", userData.webid);
    sessionStorage.setItem("userId", userData.userId);
    sessionStorage.setItem("connectId", userData.connectId); //后台登录后返回的token
    menuProcess(context, loginRes);
}

/**
 *  处理菜单赋值
 * @param commit
 * @param menu
 * @returns {Array}
 */
function assignMenuValue(eleMenu, btnsArray) {
    eleMenu = {
        ...eleMenu,
        perms: {},
        url: eleMenu.jspath,
        name: eleMenu.treeName,
        menuId: eleMenu.treeId,
    };
    // eleMenu.perms = {};
    // eleMenu.url = eleMenu.jspath;
    // eleMenu.name = eleMenu.treeName;
    // eleMenu.menuId = eleMenu.treeId;
    for (let j = 0; j < btnsArray.length; j++) {
        const eleBtn = btnsArray[j];
        if (eleMenu.tableId == eleBtn.tableId) {
            eleMenu.perms[eleBtn.action] = eleBtn.inEdit;
        }
    }
}

function everyChild(data, btnsArray) {
    if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
            assignMenuValue(data[i], btnsArray);
            if (data[i].data && data[i].data.length > 0) {
                everyChild(data[i].data, btnsArray);
            }
        }
    }
}

function dealChildMenu(menuArray, btnsArray) {
    for (let i = 0; i < menuArray.length; i++) {
        const ele_1 = menuArray[i];
        assignMenuValue(menuArray[i], btnsArray);
        if (ele_1.data && ele_1.data.length > 0) {
            everyChild(ele_1.data, btnsArray);
        }
    }
}

function selectFirstMenu(result = [], actFirstMenu, cmenus) {
    if (cmenus[0].data && cmenus[0].data.length > 0) {
        selectFirstMenu(result, actFirstMenu, cmenus[0].data);
    } else {
        result.push(cmenus[0]);
    }
    return result;
}

// 校验是否为数组json
function isJSON(str) {
    if (typeof str == "string") {
        try {
            var obj = JSON.parse(str);
            if (
                obj &&
                typeof obj === "object" &&
                str !== "{}" &&
                str !== "[]" &&
                obj.constructor === Array
            ) {
                // console.log(str + '转换成功：' + typeof obj);
                return true;
            }
        } catch (e) {
            console.log("no str");
            return false;
        }
    }
}

function isNonEmpty(value) {
    const isObject = typeof value === "object" && value !== null;
    if (Array.isArray(value)) {
        return value.length > 0;
    } else if (isObject) {
        // 使用Object.keys或者Object.getOwnPropertyNames来获取属性名
        return Object.keys(value).length > 0;
    }
    return false;
}

function objTrim(arr, field) {
    let obj = {};
    arr = arr.reduce((cur, next) => {
        obj[next[field]] ? "" : (obj[next[field]] = true && cur.push(next));
        return cur;
    }, []);
    return arr;
}

function sysStoreName(data) {
    data.forEach(one => {
        one.sysStore = one.dbName = one.jspath.split("/")[1];
        if (one.data && one.data.length > 0) {
            one.data.forEach(two => {
                two.sysStore = two.dbName = two.jspath.split("/")[1];
                if (two.data && two.data.length > 0) {
                    two.data.forEach(three => {
                        three.sysStore = three.dbName = three.jspath.split("/")[1];
                    });
                }
            });
        }
    });
    return data;
}

function afterLogout() {
    sessionStorage.clear();
    // window.location.reload();
}

// 添加系统菜单路由
// function addRouterFromSysMenu(sysName, menuData, sysMsg) {
//     if (cache[sysName]) {
//         return;
//     }
//     cache[sysName] = true;

//     if (process.env.NODE_ENV !== "production") {
//         if (!VIEW_MAP.sys[sysName]) {
//             console.error(`未配置${sysName}的页面`);
//             return;
//         }
//     }
//     const sysConfig = VIEW_MAP.sys[sysName];
//     // 自定义预处理菜单
//     if (typeof sysConfig.PROCESS_MENU === "function") {
//         menuData = sysConfig.PROCESS_MENU(menuData, sysConfig);
//     }
//     // 系统配置信息 传入 app
//     const sysData = {
//         sysHeaderLogo: sysConfig.HEADER_LOGO,
//         sysName: sysConfig.SYS_NAME,
//         sysZhName: sysConfig.SYS_ZH_NAME,
//         sysStore: sysConfig.SYS_NAME,
//         sysMenu: menuData,
//         sysMsg: sysMsg,
//     };

//     const router = {
//         path: "/" + sysName,
//         component: sysConfig.APP_LAYOUT,
//         props: {
//             sysData: sysData,
//             wpstore: sysName,
//         },
//         children: [],
//     };
//     // 默认调转页
//     if (sysConfig.HOME_PATH) {
//         // router.redirect = '/' + sysName + '/' + sysConfig.HOME_PATH
//         if (menuData && menuData.length > 0) {
//             router.redirect = menuData[0].url; //默认路由第一项
//         } else {
//             router.redirect = "/404";
//             if (!VIEW_MAP.sys[sysName]) {
//                 console.error(`未配置${sysName}的菜单`);
//                 return;
//             }
//         }
//     }
//     addChildForMenu(menuData, router.children, sysConfig);
//     console.log(router, `${sysName}------- 异步加载的路由`);
//     Router.addRoutes([router]);
//     Router.addRoutes(VIEW_MAP.staticRouter);
//     // 注册模块store
//     if (typeof sysConfig.INIT_STORE === "function") {
//         sysConfig.INIT_STORE(sysName, sysConfig.STORE, menuData, sysMsg);
//     }
// }

const tabStore = types.model("tabStore", {
    treeId: "",
    parent: "",
    treeName: "",
    tableId: 0,
    id: 0,
    jspath: "",
    sortNumber: "",
    leaf: true,
});

export const User = types
    .model("User", {
        token: types.maybeNull(types.string),
        userData: types.frozen({}),
        // 用户系统列表
        sysList: types.frozen([]),
        // 单前的系统
        activeSystem: types.frozen([]),
        // 单前菜单列表
        menuList: types.frozen([]),
        // 激活的菜单
        activeMenu: types.frozen({}),
        // 激活的子系统菜单tabs
        activeTabsMenu: types.optional(types.array(tabStore), []),
        // 全部菜单
        roleMenu: types.frozen([]),
        // 静态菜单
        staticMockMenu: types.frozen([]),
        // 基础业务类型数据
        basicBusinessDataList: types.frozen([]),
        // 基础业务类型数据-2（退回使用)
        basicBusinessDataList_2: types.frozen([])
    })
    .views(self => ({}))
    .actions(state => {
        return {
            ADD_USER_DATA: data => {
                state.userData = data;
            },
            SET_MENU_LIST(menuList) {
                state.menuList = menuList;
            },
            SET_SYS_LIST(menuList) {
                state.sysList = menuList;
            },
            SET_ACTIVE_SYSTEM: activeSystem => {
                state.activeSystem = activeSystem;
            },
            SET_ACTIVE_MENU(activeMenu) {
                if (isNonEmpty(activeMenu)) {
                    state.activeMenu = activeMenu;
                    state.activeTabsMenu.push(activeMenu);
                    state.activeTabsMenu = objTrim(state.activeTabsMenu, "jspath");
                    sessionStorage.setItem(
                        "pqsSaveActiveTabsMenu",
                        JSON.stringify(state.activeTabsMenu),
                    );
                } else {
                    console.error(activeMenu);
                }
            },
            SET_ACTIVE_TABS_MENU(tabsMenu) {
                state.activeTabsMenu = tabsMenu;
            },
            SET_BASIC_DATA_LIST(basicBusinessDataList) {
                state.basicBusinessDataList = basicBusinessDataList;
            },
            SET_BASIC_DATA_LIST_2(basicBusinessDataList) {
                state.basicBusinessDataList_2 = basicBusinessDataList;
            },
            SET_TOKEN(token) {
                state.token = token;
            },

            // 获取基础业务数据
            getBaseBusinessData() {
                return new Promise((resolve, reject) => {
                    axios({
                        method: "get",
                        url: "pqscommonSetting_query_page",
                        data: { type: 1 },
                    }).then(res => {
                        const list = res.data;
                        list.forEach((item, i) => {
                            item.options = item.options.sort((a, b) => a.sortOrder - b.sortOrder);
                            return item;
                        });
                        resolve(list);
                        state.SET_BASIC_DATA_LIST(res.data);
                    });
                });
            },
            // 获取基础业务数据
            getBaseBusinessData_2() {
                return new Promise((resolve, reject) => {
                    axios({
                        method: "get",
                        url: "pqscommonSetting_query_page",
                        data: { type: 2 },
                    }).then(res => {
                        const list = res.data;
                        list.forEach((item, i) => {
                            item.options = item.options.sort((a, b) => a.sortOrder - b.sortOrder);
                            return item;
                        });
                        resolve(list);
                        state.SET_BASIC_DATA_LIST_2(res.data);
                    });
                });
            },
            getUserData(context) {
                return new Promise((resolve, reject) => {
                    axios({
                        method: "GET",
                        url: "user",
                    })
                        .then(res => {
                            if (res.success) {
                                afterLogin(context, res);
                                resolve();
                            } else {
                                reject(res);
                            }
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            },
            getSystemMenu(info) {
                return new Promise((resolve, reject) => {
                    const sys = state.sysList[0]; //findSystem(state.sysList, info.path)
                    const sysName = "pqs"; //sys.path?sys.path.replace('/', ''):'';
                    if (cache[sysName]) {
                        state.SET_ACTIVE_SYSTEM(sys);
                        resolve();
                        return;
                    }
                    let menuArray = [],
                        btnsArray = [];
                    // 后台返回菜单
                    axios({
                        url: "/getMenus", //m_query_rolemenu
                        method: "get",
                        params: {
                            mdTypeId: sys.mdTypeId,
                        },
                    })
                        .then(res => {
                            menuArray = [...res.data];
                            const storgeTabsMenuData =
                                sessionStorage.getItem("pqsSaveActiveTabsMenu");
                            if (isJSON(storgeTabsMenuData)) {
                                const activeTabsMenu = sysStoreName(JSON.parse(storgeTabsMenuData));
                                state.SET_ACTIVE_TABS_MENU(activeTabsMenu);
                                sessionStorage.setItem(
                                    "pqsSaveActiveTabsMenu",
                                    JSON.stringify(activeTabsMenu),
                                );
                            } else {
                                let actMenu = null;
                                let actFirstMenu = menuArray[0];
                                if (info && info.tableId) {
                                    // 跳转具体页面在login-mixin.js处理高亮
                                } else {
                                    //修改重定向路由指向最下级菜单
                                    let selectMenuOne = selectFirstMenu(
                                        [],
                                        actFirstMenu,
                                        menuArray,
                                    );
                                    state.SET_ACTIVE_MENU(selectMenuOne[0]);
                                }
                            }

                            // 获取页面按钮
                            axios({
                                method: "GET",
                                url: "/getBnt",
                                params: {
                                    mdTypeId: sys.mdTypeId,
                                },
                            })
                                .then(btns => {
                                    if (btns.success) {
                                        btnsArray = btns.data;
                                    }
                                })
                                .finally(() => {
                                    // 处理将按钮权限加入menu中的perms字段
                                    dealChildMenu(menuArray, btnsArray);
                                    state.SET_MENU_LIST(menuArray);
                                    // addRouterFromSysMenu(sysName, menuArray, sys);
                                    state.SET_ACTIVE_SYSTEM(sys);
                                    resolve(res);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            },
            login(userMsg) {
                let url = "login"; // login1验证码
                let method = "POST";
                if (userMsg.keyId) {
                    url = "keyLogin";
                    method = "GET";
                } else if (userMsg.ssoId) {
                    url = "ssoLogin";
                    method = "GET";
                } else if (userMsg.authorization) {
                    url = "authorizationLogin";
                    method = "GET";
                }
                return new Promise((resolve, reject) => {
                    axios({
                        method: method,
                        customError: true,
                        _ingore: true,
                        url: url,
                        data: userMsg,
                    })
                        .then(async res => {
                            if (res.success) {
                                await afterLogin(state, res);
                                state
                                    .getSystemMenu({
                                        path: config.DEFAULT_SYS_NAME,
                                        tableId: userMsg.toMenu || null,
                                    })
                                    .then(
                                        res => {
                                            state.getBaseBusinessData().then(data => {
                                                resolve(res);
                                            });
                                            state.getBaseBusinessData_2();
                                        },
                                        e => {
                                            console.error(e);
                                            reject(e);
                                        },
                                    );
                            } else {
                                resolve(res);
                            }
                        })
                        .catch(e => {
                            console.error(e && e.msg);
                            reject(e);
                        });
                });
            },
            //keyLogin登录
            TKYlogin(userMsg) {
                let url = "keyLogin";
                let method = "GET";
                return new Promise((resolve, reject) => {
                    axios({
                        method: method,
                        customError: true,
                        _ingore: true,
                        url: url,
                        params: {
                            keyId: undefined,
                        },
                    })
                        .then(async res => {
                            if (res.success) {
                                await afterLogin(state, res);
                                state
                                    .getSystemMenu({
                                        path: config.DEFAULT_SYS_NAME,
                                        tableId: userMsg?.toMenu || null,
                                    })
                                    .then(
                                        res => {
                                            state.getBaseBusinessData().then(data => {
                                                resolve(res);
                                            });
                                            state.getBaseBusinessData_2();
                                        },
                                        e => {
                                            console.error(e);
                                            reject(e);
                                        },
                                    );
                            } else {
                                resolve(res);
                            }
                        })
                        .catch(e => {
                            console.error("===============", e && e.msg);
                            reject(e);
                        });
                });
            },
            logout(data) {
                //退出
                return new Promise((resolve, reject) => {
                    axios({
                        method: "get",
                        url: "logoutAll",
                        data: {
                            mdTypeId: config.MD_TYPE_ID || 12,
                        },
                    })
                        .then(res => {
                            if (res.success) {
                                if (data && data.isNotUploadPage) {
                                    // 不更新页面，只清除缓存
                                    sessionStorage.clear();
                                } else {
                                    afterLogout(res.data);
                                }
                            }
                            resolve(res);
                        })
                        .catch(_ => {
                            reject(_);
                        });
                });
            },
        };
    });
